package com.biscuit.page.basicservice.interceptor;

import com.biscuit.page.basicservice.conf.handler.RequestContextHandler;
import com.biscuit.page.basicservice.model.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域处理拦截器
 *
 * @author mazihao
 * @createTime 2024/4/17 13:45
 */
@Slf4j
@Component
public class CrossInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        // 获取请求类型
        String requestMethod = request.getMethod();

        // 记录请求是否为跨域处理
        RequestContext context = new RequestContext();
        context.setIsOptions(Boolean.FALSE);
        RequestContextHandler.set(context);

        // 判断请求类似是否预请求，只有预请求需要处理，非预请求不需要处理
        if ("OPTIONS".equalsIgnoreCase(requestMethod)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            // 在这里把需要处理的请求头返回
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
            response.setContentType("application/json");

            // 是否跨域
            context.setIsOptions(Boolean.TRUE);
        }

        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        RequestContextHandler.clear();
    }

}
